'use client';

import { useState, useEffect } from 'react';

interface Todo {
  id: number;
  text: string;
  completed: boolean;
}

export default function TodoList() {
  const [todos, setTodos] = useState<Todo[]>([]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [editingId, setEditingId] = useState<number | null>(null);
  const [editText, setEditText] = useState('');

  // 获取所有待办事项
  const fetchTodos = async () => {
    try {
      const response = await fetch('/api/todos');
      const data = await response.json();
      if (response.ok) {
        setTodos(data);
      } else {
        setError(data.error);
      }
    } catch (err) {
      console.error('获取待办事项失败:', err);
      setError('获取待办事项失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始加载
  useEffect(() => {
    fetchTodos();
  }, []);

  // 添加待办事项
  const addTodo = async () => {
    if (input.trim()) {
      try {
        const response = await fetch('/api/todos', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ text: input.trim() })
        });
        const data = await response.json();
        if (response.ok) {
          setTodos([...todos, data]);
          setInput('');
        } else {
          setError(data.error);
        }
      } catch (err) {
        console.error('添加待办事项失败:', err);
        setError('添加待办事项失败');
      }
    }
  };

  // 切换待办事项状态
  const toggleTodo = async (id: number, completed: boolean) => {
    try {
      const response = await fetch('/api/todos', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, completed: !completed })
      });
      const data = await response.json();
      if (response.ok) {
        setTodos(todos.map(todo =>
          todo.id === id ? data : todo
        ));
      } else {
        setError(data.error);
      }
    } catch (err) {
      console.error('更新待办事项失败:', err);
      setError('更新待办事项失败');
    }
  };

  // 删除待办事项
  const deleteTodo = async (id: number) => {
    try {
      const response = await fetch('/api/todos', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id })
      });
      const data = await response.json();
      if (response.ok) {
        setTodos(todos.filter(todo => todo.id !== id));
      } else {
        setError(data.error);
      }
    } catch (err) {
      console.error('删除待办事项失败:', err);
      setError('删除待办事项失败');
    }
  };

  // 更新任务名称
  const updateTodoText = async (id: number, newText: string) => {
    if (newText.trim()) {
      try {
        const response = await fetch('/api/todos', {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ id, text: newText.trim() })
        });
        const data = await response.json();
        if (response.ok) {
          setTodos(todos.map(todo =>
            todo.id === id ? data : todo
          ));
          setEditingId(null);
          setEditText('');
        } else {
          setError(data.error);
        }
      } catch (err) {
        console.error('更新待办事项失败:', err);
        setError('更新待办事项失败');
      }
    }
  };

  if (loading) {
    return <div className="max-w-md mx-auto p-6">加载中...</div>;
  }

  return (
    <div className="max-w-md mx-auto p-6">
      <h1 className="text-2xl font-bold mb-4">待办事项</h1>
      {error && (
        <div className="mb-4 p-2 bg-red-100 text-red-700 rounded">
          {error}
        </div>
      )}
      <div className="flex gap-2 mb-4">
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyPress={(e) => e.key === 'Enter' && addTodo()}
          placeholder="添加新的待办事项"
          className="flex-1 p-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
        />
        <button
          onClick={addTodo}
          className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          添加
        </button>
      </div>
      <ul className="space-y-2">
        {todos.map(todo => (
          <li
            key={todo.id}
            className="flex items-center justify-between p-3 bg-white rounded-lg shadow"
          >
            <div className="flex items-center gap-2 flex-1">
              <input
                type="checkbox"
                checked={todo.completed}
                onChange={() => toggleTodo(todo.id, todo.completed)}
                className="w-4 h-4 rounded focus:ring-blue-500"
              />
              {editingId === todo.id ? (
                <input
                  type="text"
                  value={editText}
                  onChange={(e) => setEditText(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && updateTodoText(todo.id, editText)}
                  onBlur={() => {
                    setEditingId(null);
                    setEditText('');
                  }}
                  className="flex-1 p-1 border rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                  autoFocus
                />
              ) : (
                <span
                  className={`flex-1 ${todo.completed ? 'line-through text-gray-500' : ''}`}
                  onDoubleClick={() => {
                    setEditingId(todo.id);
                    setEditText(todo.text);
                  }}
                >
                  {todo.text}
                </span>
              )}
            </div>
            <div className="flex gap-2">
              <button
                onClick={() => {
                  setEditingId(todo.id);
                  setEditText(todo.text);
                }}
                className="text-blue-500 hover:text-blue-700 focus:outline-none"
              >
                {editingId === todo.id ? '保存' : '编辑'}
              </button>
              <button
                onClick={() => deleteTodo(todo.id)}
                className="text-red-500 hover:text-red-700 focus:outline-none"
              >
                删除
              </button>
            </div>
          </li>
        ))}
      </ul>
    </div>
  );
}